package com.ytkj.digitalConstruction.controller.base;

import java.io.File;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ytkj.digitalConstruction.HttpResult;
import com.ytkj.digitalConstruction.service.base.FileService;

/**
 * 服务器文件请求入口
 * 
 * @author laupete
 * @date 2017年7月14日
 * @description TODO
 *
 */
@RestController
@RequestMapping("/files")
public class FileController {
	private final static Logger log = LoggerFactory.getLogger(FileController.class);

	@Autowired
	private FileService fileService;
	
	@Value("${web.head.showpath}")
	private String templateUrl;

	/**
	 * 文件上传相关代码
	 * @param file
	 * @return
	 */
	@PostMapping("/upload")
	public HttpResult upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
		if (file.isEmpty()) {
			return new HttpResult().fail().obj(file);
		}
		// 获取文件名
		File basepath = new File(request.getSession().getServletContext().getRealPath("/"));
		String fileName = UUID.randomUUID().toString().replace("-", "")+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		
		String path = basepath.getParent()+"/"+templateUrl;
		if (!fileService.saveResource(file, fileName, path)) {
			log.error("file save failure.");
			return new HttpResult().fail();
		}
		return new HttpResult().success().msg("file:" + fileName).obj(templateUrl+"/"+fileName);
	}
	
	
	/**
	 * 获取文件
	 * 
	 * @param filename
	 * @return
	 */
	@GetMapping(value = "/{filename:.+}")
	public ResponseEntity<?> getFile(@PathVariable String filename) {
		try {
			return ResponseEntity.ok(fileService.getResource(filename));
		} catch (Exception e) {
			return ResponseEntity.notFound().build();
		}
	}

}